package com.qb.devserv;

import static com.qb.devserv.MainService.mService;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.RecoverySystem;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xuexiang.xui.XUI;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;

import utils.DevActionUtil;
import utils.DevInfoUtil;
import utils.MyUtil;

public class SystemActivity extends AppCompatActivity {

    Context ctx;
    TextView tvTitle,tvContent;
    Button btnClose;
    ProgressBar pb;
    String flag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        XUI.initTheme(this);
        XToast.Config.get().setGravity(Gravity.CENTER);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_system);
        StatusBarUtils.initStatusBarStyle(this, false, 0x00000000);
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        this.getWindow().setAttributes(lp);
        ctx = SystemActivity.this;

        tvTitle = findViewById(R.id.tv_sys_title);
        tvContent = findViewById(R.id.tv_sys_content);
        pb = findViewById(R.id.pb_sys);

        btnClose = findViewById(R.id.btn_close);
        btnClose.setOnClickListener(view -> {
            finish();
        });

        Intent exStr = this.getIntent();
        flag =  exStr.getStringExtra("flag");
        if (flag.equals("update")) {
            tvTitle.setText("系统固件升级");
            tvContent.setText("正在校验固件升级文件");
            new Handler().postDelayed(()-> {
                systemUpdate(ctx,"update.zip");
            },5000);
        } else {
            btnClose.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 系统升级固件
     */
    public void systemUpdate(Context ctx, String fileName) {
        File updateFile = DevActionUtil.getFileByPath(DevActionUtil.getRomPath()+fileName,false);
        try {
            //签名校验
            RecoverySystem.verifyPackage(updateFile, new RecoverySystem.ProgressListener() {
                @Override
                public void onProgress(int progress) {
                    MyUtil.showLog("签名校验进度:" + progress,"");
                    runOnUiThread(()->{
                        tvContent.setText("正在校验固件升级文件"+progress+"%");
                    });
                }
            }, null);
            //升级
            try {
                installPackage(ctx, updateFile);
            } catch (Exception e) {
                failShowHint(e.getMessage());
                e.printStackTrace();
            }
        } catch (GeneralSecurityException e) {
            failShowHint(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            failShowHint(e.getMessage());
            e.printStackTrace();
        }
    }

    private void failShowHint(String err) {
        tvContent.setText("系统升级失败，"+err);
        pb.setVisibility(View.GONE);
        btnClose.setVisibility(View.VISIBLE);
        delayFinish();
    }

    private void installPackage(Context context, File packageFile) throws IOException {
        String oriPath = packageFile.getCanonicalPath();
        String convertPath = oriPath;
        if (Build.VERSION.SDK_INT >= 30) { // Build.VERSION_CODES.R
            MyUtil.showLog("installPackage", "installPackage SDK version >= Build.VERSION_CODES.R,should convert update file path.");
            if (oriPath.startsWith("/storage/emulated/0")) {
                convertPath = oriPath.replace("/storage/emulated/0", "/data/media/0");
            } else if (oriPath.startsWith("/storage")) {
                convertPath = oriPath.replace("/storage", "/mnt/media_rw");
            }
            MyUtil.showLog("installPackage", "installPackage update " + oriPath + " to " + convertPath);
            File convertFile = new File(convertPath);
            String sn = DevInfoUtil.getSN();
            //mService.mu.publishMessage("/MyTest/DevServe/DevQuery/ReQuery",sn);
            RecoverySystem.installPackage(context, convertFile);
        } else {
            String sn = DevInfoUtil.getSN();
            //mService.mu.publishMessage("/MyTest/DevServe/DevQuery/ReQuery",sn);
            RecoverySystem.installPackage(context, packageFile);
        }
    }

    public void delayFinish() {
        new Handler().postDelayed(()-> {
//            finish();
        },6000);
    }
}